﻿Imports System.IO
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.Runtime.Serialization

Public Class CloneHelper

    Public Shared Function DeepClone(Of T)(ByVal inputObj As T) As T
        Return DeepClone(inputObj, Nothing)
    End Function

    Public Shared Function DeepClone(Of T)(ByVal inputObj As T, options As Dictionary(Of String, String)) As T
        Using memStrm As New MemoryStream(1024 * 10)
            Dim binFormatter As New BinaryFormatter(Nothing, New StreamingContext(StreamingContextStates.Clone, options))
            binFormatter.Serialize(memStrm, inputObj)
            memStrm.Seek(0, SeekOrigin.Begin)
            Try
                Return DirectCast(binFormatter.Deserialize(memStrm), T)
            Catch ex As Exception
                Trace.TraceError(ex.Message)
                Return Nothing
            End Try
        End Using
    End Function


    Public Shared Function GetOption(context As StreamingContext, optionName As String) As String
        Return GetOption(context, optionName, "")
    End Function

    Public Shared Function GetOption(context As StreamingContext, optionName As String, defaultValue As String) As String
        Dim options As Dictionary(Of String, String) = CType(context.Context, Dictionary(Of String, String))
        If options Is Nothing Then
            Return defaultValue
        End If
        If options.ContainsKey(optionName) Then
            Return options(optionName)
        End If
        Return defaultValue
    End Function
End Class
